package com.chcit.mobile.mvp.shipment.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chcit.custom.view.loader.QuickLoader;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.loader.LoadingDialog;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.chcit.custom.view.toolbar.CommonToolbar;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.di.component.DaggerScanPackageComponent;
import com.chcit.mobile.mvp.entity.ShipmentBean;
import com.chcit.mobile.mvp.common.adapter.PackageScanAdapter;
import com.chcit.mobile.mvp.common.contract.ScanPackageContract;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.chcit.mobile.mvp.common.presenter.ScanPackagePresenter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import org.apache.commons.lang3.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 采购出库 包装扫码拣货方式
 */
public class ShipmentScanPackageFragment extends ScanFragment<ScanPackagePresenter> implements ScanPackageContract.View {

    @BindView(R.id.common_toolbar)
    CommonToolbar commonToolbar;
    @BindView(R.id.tiet_shipment_scan_no)
    SuperInputEditText tietNo;
    @BindView(R.id.tv_shipment_scan_unitPackQty)
    TextView tvUnitPackQty;//定数
    @BindView(R.id.tv_shipment_scan_guaranteDate)
    TextView tvGuaranteDate;//效期
    @BindView(R.id.tv_shipment_scan_productCode)
    TextView tvProductCode;//效期
    @BindView(R.id.tv_shipment_scan_productname)
    TextView tvProductname;
    @BindView(R.id.tv_shipment_scan_lot)
    TextView tvLot;
    @BindView(R.id.tv_shipment_scan_productSpec)
    TextView tvProductSpec;
    @BindView(R.id.tv_shipment_scan_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.tv_shipment_scan_qtyTarget)
    TextView tvQtyTarget;//指示数量
    @BindView(R.id.tv_shipment_scan_qtyPicked)
    TextView tvQtyPicked;//已拣数量
    @BindView(R.id.tv_shipment_scan_qtyLeft)
    TextView tvQtyLeft;//待拣数量
    @BindView(R.id.dr_shipment_scan_locator)
    EditSpinner spinnerLocator;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.rv_receive_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.tl_tabs)
    TabLayout tlTabs;
    @BindView(R.id.bt_shipment_scan_ok)
    Button btOk;

    private BigDecimal  qtyLeft, qtyPicked;
    private List<PackageBean> donePackageBeans = new ArrayList<>();
    private PackageScanAdapter doneScanAdapter;
    private List<PackageBean> unPackageBeans = new ArrayList<>();
    private PackageScanAdapter unScanAdapter;
    private ShipmentBean mShipmentBean;



    public static ShipmentScanPackageFragment newInstance(ShipmentBean shipmentBean) {
        ShipmentScanPackageFragment fragment = new ShipmentScanPackageFragment();
        fragment.mShipmentBean = shipmentBean;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerScanPackageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shipment_scan_package, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        showTaskInfo();

    }


    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
       QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
       QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {

            tietNo.setText(barcodeData);
            checkPackageNo(barcodeData);

    }

    @SuppressLint("SetTextI18n")
    private void showTaskInfo() {
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l->{
            assert mPresenter != null;
            if(mPresenter.isError){
                setFragmentResult(RESULT_OK,new Bundle());
            }
            pop();
        });

        tvManufacturer.setText(mShipmentBean.getManufacturer());
        mCommonToolbar.setTitleText(mShipmentBean.getOrderTypeName()+"出库");
        tvLot.setText(mShipmentBean.getLot());
        tvProductname.setText(mShipmentBean.getProductName());
        tvProductSpec.setText(mShipmentBean.getProductSpec());
        tvProductCode.setText(mShipmentBean.getProductCode());
        if(ObjectUtils.anyNotNull(mShipmentBean.getUnitPackQty())){
            tvUnitPackQty.setText(mShipmentBean.getUnitPackQty().toString());
        }
        tvQtyTarget.setText(mShipmentBean.getQtyTarget()+mShipmentBean.getUomName());
        tvGuaranteDate.setText(mShipmentBean.getGuaranteeDate());
        if(mShipmentBean.getQtyLeft() != null){
            qtyLeft = mShipmentBean.getQtyLeft();

        }else{
            qtyLeft = new BigDecimal(0);
        }
        tvQtyLeft.setText(qtyLeft.toString()+mShipmentBean.getUomName());
        if(mShipmentBean.getQtyPicked() != null){
            qtyPicked = mShipmentBean.getQtyPicked();

        }else{
            qtyLeft = new BigDecimal(0);
        }
        tvQtyPicked.setText(qtyPicked+mShipmentBean.getUomName());


       /* tvGuaranteDate.setText(mShipmentBean.getReceivePackageNum().toString());
        if (mShipmentBean.getReceivedPackageNum() != null) {
            receivedPackageNum = mShipmentBean.getReceivedPackageNum();
            tvReceivedPackageNum.setText(mShipmentBean.getReceivedPackageNum().toString());
        } else {
            receivedPackageNum = new BigDecimal(0);
        }
        if (mShipmentBean.getReceivedNum() != null) {
            qtyPicked = mShipmentBean.getReceivedNum();
            tvReceivedNum.setText(mShipmentBean.getReceivedNum() + mShipmentBean.getUomName());//已收数量
        } else {
            qtyPicked = new BigDecimal(0);
            tvReceivedNum.setText(qtyPicked + mShipmentBean.getUomName());//已收数量
        }

        if (mShipmentBean.getQtyLeft() != null) {
            tvReceiveNum.setText(mShipmentBean.getQtyLeft().toString() + mShipmentBean.getUomName());//到货数量
        }

        if (mShipmentBean.getRejectedReceiveNum() != null) {
            tvRejectedNum.setText(mShipmentBean.getRejectedReceiveNum().toString() + mShipmentBean.getUomName());
        }

        if (mShipmentBean.getRejectedReceivePackageNum() != null) {
            tvRejectedPackageNum.setText(mShipmentBean.getRejectedReceivePackageNum().toString());
        } else {
            tvRejectedPackageNum.setText("0" + mShipmentBean.getUomName());
        }
        if (mShipmentBean.getWaitReceiveNum() != null) {
            qtyLeft = mShipmentBean.getWaitReceiveNum();
            tvWaitReceiveNum.setText(mShipmentBean.getWaitReceiveNum() + mShipmentBean.getUomName());//待收
        } else {
            qtyLeft = mShipmentBean.getQtyArrived().subtract(qtyPicked);
        }

        if (mShipmentBean.getPackageCountConfirmLeft() != null) {
            waitReceivePackageNum = mShipmentBean.getPackageCountConfirmLeft();
            tvWaitPackageNum.setText(waitReceivePackageNum.toString());

        } else {
            waitReceivePackageNum = new BigDecimal(0);
        }
*/

    }

    PackageBean packageBean;

    private void checkPackageNo(String packageNo) {

        if (tlTabs.getSelectedTabPosition() != 0) {
            Objects.requireNonNull(tlTabs.getTabAt(0)).select();
        }
        packageBean = new PackageBean(packageNo);
        int itemPosition = donePackageBeans.indexOf(packageBean);
        if (itemPosition >= 0) {
            final int i = itemPosition;
            new MaterialDialog.Builder(mContext)
                    .content("该包装已扫过，是否删除改包装？")
                    .positiveText("是")
                    .negativeText("否")
                    .onPositive((dialog, which) -> {
                        packageBean = donePackageBeans.get(i);
                        doneScanAdapter.remove(i);
                        updateSubstractPackageInfo(packageBean);
                    }).show();
        } else {
            if (qtyLeft.intValue() <= 0) {
                String message = "<font color='#FF0000'><big>该任务要求的包装数量扫描完毕！</big></font><br/>(如需替换，请重新输入要替换的包装将该包装移除出已扫包装列表！)";
                 new MaterialDialog.Builder(mContext)
                        .content(Html.fromHtml(message))
                        .title("提示")
                        .positiveText("确认")
                        .show();
                return;
            }
            JSONObject data = new JSONObject();
            //data.put("asnId", mShipmentBean.getAsnId());//
            //data.put("asnLineId", mShipmentBean.getAsnLineId());
            data.put("pickListId", mShipmentBean.getPickListId());
            data.put("pickListJobId", mShipmentBean.getPickListJobId());
            data.put("packageNo", packageNo);
            assert mPresenter != null;
            mPresenter.verifyPickListPackage(data, list ->{//扫描的包装定数数量超过待拣数量
                packageBean = list.get(0);
                if(packageBean.getUnitPackQty().subtract(qtyLeft).intValue()>0){//
                    DialogUtil.showErrorDialog(mContext,"该包装的商品数量大于待拣数量！");
                    return;
                }
                doneScanAdapter.addData(packageBean);
                updateAddPackageInfo(packageBean);
                if(qtyLeft.intValue() == 0){
                    String message = "<font color='#FF0000'><big>该任务要求的包装数量扫描完毕，是否确认出库！</big></font>";
                    MaterialDialog materialDialog =  new MaterialDialog.Builder(mContext)
                            .title("确认出库")
                            .content(Html.fromHtml(message))
                            .positiveText("是")
                            .negativeText("否")
                            .onPositive((dialog, which) -> {
                                btOk.performClick();
                            })
                            .build();
                    materialDialog.getActionButton(DialogAction.POSITIVE).setTextSize(18);
                    materialDialog.getActionButton(DialogAction.NEGATIVE).setTextSize(18);
                    materialDialog.show();
                }
            });

        }
        //{pickListId:"1212",pickListJobId：121212,packageNo"232323dfdf"}

    }

    /**
     * 增加包装
     * @param packageBean 包装信息
     */
    @SuppressLint("SetTextI18n")
    private void updateAddPackageInfo(PackageBean packageBean) {
        //waitReceivePackageNum = waitReceivePackageNum.subtract(new BigDecimal(1));
        //receivedPackageNum = receivedPackageNum.add(new BigDecimal(1));
        qtyLeft = qtyLeft.subtract(packageBean.getUnitPackQty());
        qtyPicked = qtyPicked.add(packageBean.getUnitPackQty());
        tvQtyLeft.setText(qtyLeft.toString() + mShipmentBean.getUomName());
        tvQtyPicked.setText(qtyPicked.toString() + mShipmentBean.getUomName());
    }

    /**
     * 移除包装
     *
     * @param packageBean 包装信息
     */
    @SuppressLint("SetTextI18n")
    private void updateSubstractPackageInfo(PackageBean packageBean) {
        //waitReceivePackageNum = waitReceivePackageNum.add(new BigDecimal(1));
        //receivedPackageNum = receivedPackageNum.subtract(new BigDecimal(1));
        qtyLeft = qtyLeft.add(packageBean.getUnitPackQty());
        qtyPicked = qtyPicked.subtract(packageBean.getUnitPackQty());

        //tvWaitPackageNum.setText(waitReceivePackageNum.toString());
        tvQtyLeft.setText(qtyLeft.toString() + mShipmentBean.getUomName());
        //tvReceivedPackageNum.setText(receivedPackageNum.toString());
        tvQtyPicked.setText(qtyPicked.toString() + mShipmentBean.getUomName());
    }

    private void initUnScanRecyclerView() {
        unScanAdapter = new PackageScanAdapter(unPackageBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        unScanAdapter.setOnItemClickListener((adapter, view, position) -> {
            if(unScanAdapter.getthisPosition() >=0){
                unScanAdapter.notifyItemChanged(unScanAdapter.getthisPosition());
            }
            unScanAdapter.setThisPosition(position);
            PackageBean packageBean =  unScanAdapter.<PackageBean>getData().get(position);

            unScanAdapter.notifyItemChanged(unScanAdapter.getthisPosition());
            new MaterialDialog.Builder(mContext)
                    .content("确认拣该包装吗？")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive((dialog, which) -> onBarcodeEventSuccess(packageBean.getPackageNo())).show();
        });


    }
    private void initDoneScanRecyclerView() {
        doneScanAdapter = new PackageScanAdapter(donePackageBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        doneScanAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            int itemClickPosition = -1;

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (itemClickPosition >= 0) {
                    doneScanAdapter.notifyItemChanged(doneScanAdapter.getthisPosition());
                    doneScanAdapter.setThisPosition(position);
                    itemClickPosition = position;
                    // PackageBean packageBean= (PackageBean) adapter.getData().get(position);
                    doneScanAdapter.notifyItemChanged(doneScanAdapter.getthisPosition());
                }

            }
        });
        mRecyclerView.setAdapter(doneScanAdapter);


    }

    private void initEvent() {
        tietNo.setOnKeyListener(new View.OnKeyListener() {
            private static final int LIMIT_TIME = 300;
            private long lastClickTime = 0;

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                long curTime = Calendar.getInstance().getTimeInMillis();
                if (curTime - lastClickTime > LIMIT_TIME) {
                    lastClickTime = curTime;
                    if (keyCode == KeyEvent.KEYCODE_ENTER && !Objects.requireNonNull(tietNo.getText()).toString().isEmpty()) {
                        onBarcodeEventSuccess(tietNo.getText().toString());
                        return true;
                    } else {
                        return false;
                    }

                }
                return false;

            }
        });
        tlTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            int i = 0;
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                switch (tab.getPosition()) {
                    case 0:
                        mRecyclerView.setAdapter(doneScanAdapter);
                        break;
                    case 1:
                        if(i == 0){
                            i++;
                            getData();
                        }else{
                            mRecyclerView.setAdapter(unScanAdapter);
                        }

                        break;
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void getData() {

        JSONObject data = new JSONObject();
        /*{pickListId:"1212",pickListJobId：121212,packageNo:["2323","232323dfdf"]}*/
        data.put("pickListJobId", mShipmentBean.getPickListJobId());
        assert mPresenter != null;
        mPresenter.getPakcageInfo(HttpMethodContains.SHIPMENT_PACKAGE_QUERY,data, list -> {
                unScanAdapter.addData(list);
                mRecyclerView.setAdapter(unScanAdapter);
        });

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initSpinner();
        initEvent();
        initUnScanRecyclerView();
        initDoneScanRecyclerView();
    }

    private void initSpinner() {
        spinnerLocator.setText(mShipmentBean.getFromLocatorValue());
        spinnerLocator.getEditText().setEnabled(false);
       /* spinnerLocator.setImageOnClickListener(new View.OnClickListener() {
            int i = 0;

            @Override
            public void onClick(View v) {
                if (i == 0) {
                    i++;
                    JSONObject data = new JSONObject();
                    data.put("productId", mShipmentBean.getProductId());
                    data.put("showStorageLoc", "");
                    mPresenter.getLocators(data, list -> {
                        locators = list;
                        locator = locators.get(0);
                        spinnerLocator.setItemData(locators);
                        spinnerLocator.setOnItemChageClickListener((parent, view, position, id) -> {
                            if (position >= 0) {
                                locator = locators.get(position);
                            }
                        });
                        v.performClick();

                    });
                }
            }
        });
        JSONObject data = new JSONObject();
        data.put("productId", mShipmentBean.getProductId());
        data.put("showBigLoc", "Y");
        mPresenter.getLocators(data, list -> {
            if (list.size() > 0) {
                locator = list.get(0);
                spinnerLocator.setText(locator.getName());
            }

        });*/

    }

    @Override
    protected void initToolBar() {
        super.initToolBar();
        /*mCommonToolbar.<TextView>getRightMenuView(0).setText("重新拣货");
        mCommonToolbar.<TextView>getRightMenuView(0).setOnClickListener(l -> {
            if (donePackageBeans.size() > 0) {
                assert mPresenter != null;
                mPresenter.queryListData(new Consumer<List<Statu>>() {
                    int i = 0;
                    @Override
                    public void accept(List<Statu> status) {

                        new MaterialDialog.Builder(mContext)
                                .title("拒收原因")
                                .items(status)
                                .itemsCallbackSingleChoice(i, (dialog, itemView, which, text) -> {
                                    i = which;
                                    // {asnId:"1212",asnLineId:12123,rejectReason:"test",packageNo:["2323","232323dfdf"]}
                                    JSONObject data = new JSONObject();
                                    //data.put("asnId", mShipmentBean.getAsnId());//
                                    //data.put("asnLineId", mShipmentBean.getAsnLineId());
                                    data.put("rejectReason", status.get(i));
                                    JSONArray packageNos = new JSONArray();
                                    for (PackageBean p : donePackageBeans) {
                                        packageNos.add(p.getPackageNo());
                                    }
                                    data.put("packageNo", packageNos);
                                    mPresenter.rejectAsnPackage(data, () -> {
                                        showMessage("拒收处理成功！");
                                        pop();
                                    });
                                    return true;
                                }).neutralText("取消")
                                .positiveText("确认")
                                .build()
                                .show();
                    }
                });
            } else {
                DialogUtil.showErrorDialog(mContext,"请选择拒收包装");
            }
        });*/
    }


    @OnClick(R.id.bt_shipment_scan_ok)
    public void onViewClicked() {
        if (donePackageBeans.size() > 0) {
          /*  if(locator ==null || !locator.getValue().equals(spinnerLocator.getText())){
                showMessage("请输入货位");
                return;
            }*/
            JSONObject data = new JSONObject();
           /* if("Y".equals(mShipmentBean.getIsControlledProduct())) {

                ShipmentFragment fragment = (ShipmentFragment) getPreFragment();
                if (fragment != null && fragment.getUser() == null) {
                    HttpClientHelper.showSelectSecondChangeDialog(getActivity(), (dialog, user) -> {
                        fragment.setUser(user);
                        data.put("workerId2", fragment.getUser().getId());
                        submit(data);
                    });
                    return;
                } else {
                    data.put("workerId2", fragment.getUser().getId());
                }
            }*/
            submit(data);
        }else{
            DialogUtil.showErrorDialog(mContext,"请扫码需要操作的包装后，在点击确认！");
        }
    }

    private void submit(JSONObject data) {
        data.put("pickListId", mShipmentBean.getPickListId());//
        data.put("pickListJobId", mShipmentBean.getPickListJobId());
        JSONArray packageNos = new JSONArray();
        for (PackageBean p : donePackageBeans) {
            packageNos.add(p.getPackageNo());
        }
        data.put("packageNo", packageNos);
        // {pickListId:"1212",pickListJobId：121212,packageNo:["2323","232323dfdf"]}
        assert mPresenter != null;
        mPresenter.pickPackage(data,()->{
            if(qtyLeft.intValue() == 0){
                showMessage("处理成功");
                setFragmentResult(RESULT_OK,null);
                pop();
            }else{
                new MaterialDialog.Builder(mContext)
                        .content("任务还没完成，是否继续？")
                        .neutralText("是")
                        .positiveText("否")
                        .onNeutral((dialog, which) -> {
                            donePackageBeans.clear();
                            doneScanAdapter.notifyDataSetChanged();
                        })
                        .onPositive((dialog, which) -> {
                            setFragmentResult(RESULT_OK,new Bundle());
                            pop();
                        }).show();

            }

        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        doneScanAdapter = null;


    }

}
